import request, { extend } from 'umi-request';
import { message } from 'antd';

const errorHandler = function (error) {
  const codeMap = {
    '021': '发生错误啦',
    '022': '发生大大大大错误啦',
    // ....
  };
  if (error.response.status > 400) {
    // 请求已发送但服务端返回状态码非 2xx 的响应
    // console.log(error.data);
    message.error(error.data)
  } else {
    // 请求初始化时出错或者没有响应返回的异常
    // console.log(error.message);
    message.error('network error')
  }

  throw error; // 如果throw. 错误将继续抛出.
};

// 1. 作为统一错误处理
const extendRequest = extend({ errorHandler });

async function getUserList() {
  return extendRequest('/api/users', {
    method: 'get',
  }).then(function (response) {
    // console.log(response);
    message.success('get ok')
    return response;
  }).catch(function (error) {
    // console.log(error);
    message.error('get error')
    return false
  });
}

const editRecord = async (id, values) => {
  request(`/api/users/${id}`, {
    method: 'put',
    data: values,
  })
    .then(function (response) {
      // console.log('ok');
      message.success('edit ok')
    })
    .catch(function (error) {
      // console.log(error);
      message.error('edit failed')
    });
}

const deleteRecord = async (id) => {
  request(`/api/users/${id}`, {
    method: 'delete',
  })
    .then(function (response) {
      // console.log('delete ok');
      message.success('delete ok')
    })
    .catch(function (error) {
      // console.log(error);
      message.error('delete failed')
    });
}

const addRecord = async (values) => {
  request(`/api/users`, {
    method: 'post',
    data: values,
  })
    .then(function (response) {
      // console.log('ok');
      message.success('add ok')
    })
    .catch(function (error) {
      // console.log(error);
      message.error('add failed')
    });
}

export { getUserList, editRecord, deleteRecord, addRecord };
